<template>
    <div>
        <el-form label-width="80px">
            <el-form-item label="SPU名称" :model="spu">
                <el-input placeholder="SPU名称" style="width: 400px;" v-model="spu.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select placeholder="请选择品牌" v-model="spu.tmId">
                    <el-option :label="tm.tmName" :value="tm.id" v-for="(tm, index) in tradeMarkList" :key="index">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" placeholder="SPU名称" rows="4" v-model="spu.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <!-- 上传图片 
                action:上传地址；
                list-type：（picture-card） 文件列表类型 （照片墙类型）
                on-preview：浏览图片时触发
                on-remove：删除图片时触发
                file-list:当前页面展示照片
                -->
                <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card" :file-list='spuImageList'
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handlerSuccess">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <!--  -->
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">

                <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                    <el-option :label="unselect.name" :value="`${unselect.id}:${unselect.name}`"
                        v-for="(unselect, index) in unSelectSaleAttr" :key="unselect.id"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性
                </el-button>

                <el-table border :data="spu.spuSaleAttrList">
                    <el-table-column type="index" label="序号" width="80" align="center">
                    </el-table-column>
                    <el-table-column prop="saleAttrName" label="属性名" width="width">
                    </el-table-column>
                    <el-table-column prop="prop" label="属性值名称列表" width="width">
                        <template slot-scope="{row,$index}">
                            <!-- 属性名 -->
                            <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable
                                :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                                {{ tag.saleAttrValueName }}
                            </el-tag>

                            <!-- 属性值 -->
                            <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                ref="saveTagInput" size="small" @keyup.enter.native="$event.target.blur"
                                @blur="handleInputConfirm(row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加
                            </el-button>

                        </template>
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="width">
                        <el-button type="danger" icon="el-icon-delete" size='mini'
                            @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: 'SpuForm',
    data() {
        return {
            dialogImageUrl: "",
            dialogVisible: false,
            spu: {              //存储SPU信息属性
                category3Id: 0,     //三级分类的id
                description: "",    //描述
                spuName: "",        //spu名称
                tmId: '',             //平台的id
                spuImageList: [      //收集SPU图片的信息
                    // {   
                    // id:0,
                    // imgName:'',
                    // imgUrl:'',
                    // spuId:0,
                    // }
                ],
                spuSaleAttrList: [   //平台属性与属性值收集
                    // {
                    // baseSaleAttrId:0,
                    // id:0,
                    // idChecked:'',
                    // saleAttrName:'',
                    // saleAttrValueName:'',
                    // spuId:0,
                    // }
                ],
            },
            tradeMarkList: [],   //存储品牌信息
            spuImageList: [],    //存储SPU图片的数据
            saleAttrList: [],    //销售属性的数据
            attrIdAndAttrName: '',     //收集未选择的销售属性的id和name
        };
    },

    mounted() {

    },

    methods: {
        //初始化SpuForm数据
        async initSpuData(spu) {
            //spu是父组件点击修改按钮对应的spu数据
            //获取SPU信息的数据
            let spuResult = await this.$API.spu.reqSpu(spu.id);
            if (spuResult.code == 200) {
                this.spu = spuResult.data;
            }
            //获取品牌的信息
            let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
            if (tradeMarkResult.code == 200) {
                this.tradeMarkList = tradeMarkResult.data;
            };
            //获取SPU图片的数据
            let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
            if (spuImageResult.code == 200) {
                let listArr = spuImageResult.data;
                //照片墙显示图片的数据要有[name:'',url:'']，接口给的为[imaName:'',imgUrl:''],加工一下
                listArr.forEach(item => {
                    item.name = item.imgName;
                    item.url = item.imgUrl;
                });
                //把整理好后的数据赋予
                this.spuImageList = listArr;
            };
            //获取平台全部销售属性  --最多三个
            let saleResult = await this.$API.spu.reqBaseSaleAttrList();
            if (saleResult.code == 200) {
                this.saleAttrList = saleResult.data;
            };
        },
        //照片墙删除触发
        handleRemove(file, fileList) {
            //file：删除的那张图片
            //fileList：删除那张图片后剩下的图片
            //收集删除后图片数据
            //数据里有name、url字段，提交给服务器时要删掉
            this.spuImageList = fileList;
        },
        //照片墙图片预览回调
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //图片上传成功的回调
        handlerSuccess(response, file, fileList) {
            //response：服务器发回来的一些信息
            //file:上传成功的图片
            //fileList：全部上传的图片
            this.spuImageList = fileList;
        },
        //添加新的销售属性
        addSaleAttr() {
            //结构赋值  用[]？ 
            const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':');
            //向spu里的spuSaleAttrList属性里加入新的销售属性
            let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
            //添加新的销售属性
            this.spu.spuSaleAttrList.push(newSaleAttr)
            //清空数据
            this.attrIdAndAttrName = '';
        },
        //属性值的添加按钮
        addSaleAttrValue(row) {
            //row:当前销售属性
            //点击销售属性值当中添加按钮时，button变为input，通过控制当前销售属性（row）的inputVisible
            //row不是响应式数据用这种方法变为响应式数据
            this.$set(row, 'inputVisible', true);
            //通过响应式数据inputValue字段收集新增的销售属性值
            this.$set(row, 'inputValue', '');
        },
        //el-input失去焦点的事件
        handleInputConfirm(row) {
            //结构赋值
            const { baseSaleAttrId, inputValue } = row;
            //inputValue不能为空
            if (inputValue.trim() == '') {
                this.$message({ message: '属性值不能为空', type: 'warning' });
                return;
            }
            //属性值不能重复
            let result = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == inputValue)
            if (result) {
                this.$message({ message: '已经有该属性值了', type: 'warning' });
                return;
            }
            //新增的属性值
            let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
            //新增
            row.spuSaleAttrValueList.push(newSaleAttrValue)
            //隐藏input，显示button
            row.inputVisible = false;
        },
        //保存按钮回调
        async addOrUpdateSpu() {
            //整理照片墙数据，把spuImageList里的图片的
            //接口要求携带参数发请求需要有imgUrl，imgName字段
            //在spuImageList里加入imgUrl，imgName字段然后整理到spu.spuImageList里
            this.spu.spuImageList = this.spuImageList.map((item) => {
                return {
                    imgName: item.name,
                    imgUrl: (item.response && item.response.data) || item.url,
                }
            })
            //发请求
            let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
            if (result.code == 200) {
                this.$message({
                    message: '保存成功',
                    type: 'success'
                })
            } else {
                this.$message({
                    message: '保存失败',
                    type: 'warring'
                })
            }
            this.$emit('changeScene', {scene:0,flag:this.spu.id?'修改':'添加' });
            //清除数据
            Object.assign(this._data, this.$options.data());
        },
        //点击添加SPU按钮，发请求
        async addSpuData(category3Id) {
            this.spu.category3Id = category3Id;
            //获取品牌的信息
            let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
            if (tradeMarkResult.code == 200) {
                this.tradeMarkList = tradeMarkResult.data;
            };
            //获取平台全部销售属性  --最多三个
            let saleResult = await this.$API.spu.reqBaseSaleAttrList();
            if (saleResult.code == 200) {
                this.saleAttrList = saleResult.data;
            };
        },
        //取消按钮
        cancel() {
            //切换场景
            this.$emit('changeScene', {scene:0,flag:''});
            //清除数据
            //Object.assign:es6语法,合并对象
            //这两个对象都是初始数据？
            Object.assign(this._data, this.$options.data());
        }
    },
    computed: {
        //计算出还没选择的销售属性
        unSelectSaleAttr() {
            //saleAttrList有三个销售属性
            //过滤并返回还没选择的销售属性
            let result = this.saleAttrList.filter(item => {
                //this.spu.spuSaleAttrList是已经被选择了的属性
                //every方法，返回布尔值
                return this.spu.spuSaleAttrList.every(item1 => {
                    return item.name != item1.saleAttrName;
                })
            })
            return result;
        },
    },

};
</script>

<style  scoped>
.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>